package com.huanzhidadi.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {

    /**
     * direct模式发送简单消息
     * @return
     */
    @Bean
    public Queue directPushMessageQueue() {
        return new Queue("directPushMessage");
    }

    /**
     * direct模式发送对象
     * @return
     */
    @Bean
    public Queue directPushObjectQueue() {
        return new Queue("directPushObject");
    }


    // topic开始
    @Bean
    TopicExchange exchange() {
        return new TopicExchange("topicExchange");
    }

    /**
     * topic.a
     * @return
     */
    @Bean
    public Queue topicAQueue() {
        return new Queue("topic.a");
    }

    /**
     * topic.all
     * @return
     */
    @Bean
    public Queue topicAllQueue() {
        return new Queue("topic.all");
    }

    /**
     * 这里的入参需要和上面定义的队列和交换机方法名一致，否则会提示无法绑定
     * @param topicAQueue
     * @param exchange
     * @return
     */
    @Bean
    Binding bindingExchangetopicA(Queue topicAQueue, TopicExchange exchange) {
        return BindingBuilder.bind(topicAQueue).to(exchange).with("topic.a");
    }

    @Bean
    Binding bindingExchangetopicAll(Queue topicAllQueue, TopicExchange exchange) {
        return BindingBuilder.bind(topicAllQueue).to(exchange).with("topic.#");
    }
    // topic结束


    // 广播开始
    @Bean
    FanoutExchange fanoutExchange() {
        return new FanoutExchange("fanoutExchange");
    }

    @Bean
    public Queue fanoutQueueA() {
        return new Queue("fanoutA");
    }

    @Bean
    public Queue fanoutQueueB() {
        return new Queue("fanoutB");
    }

    @Bean
    Binding bindingExchangeFanoutA(Queue fanoutQueueA, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(fanoutQueueA).to(fanoutExchange);
    }

    @Bean
    Binding bindingExchangeFanoutB(Queue fanoutQueueB, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(fanoutQueueB).to(fanoutExchange);
    }

    // 广播结束

    /**
     * 延迟消息交换机
     * @return
     */
    @Bean
    public CustomExchange delayExchange() {
        Map<String, Object> args = new HashMap<>();
        // 设置自定义交换器路由消息的类型，direct类似direct交换器路由消息的模式，也可以传递topic、fanout,或者其它插件提供的自定义的交换器类型
        args.put("x-delayed-type", "direct");
        return new CustomExchange("delayed_exchange", "x-delayed-message", true, false, args);
    }

    @Bean
    public Queue delayedQueue() {
        return new Queue("delay_queue_1");
    }

    /**
     * 延迟队列绑定交换器
     */
    @Bean
    public Binding bindingDelayCustomExchangeQueue(Queue delayedQueue, CustomExchange delayExchange){
        return BindingBuilder.bind(delayedQueue).to(delayExchange).with("delay_routing_key").noargs();
    }
}
